package com.elinkway.infinitemovies.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.elinkway.infinitemovies.adapter.ReportPhotoAdapter;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.http.requesttask.UploadImageTask;
import com.elinkway.infinitemovies.http.requesttask.uploadReportPictureTask;
import com.elinkway.infinitemovies.listener.OnReportListener;
import com.elinkway.infinitemovies.ui.activity.AlbumActivity;
import com.elinkway.infinitemovies.ui.activity.ReportActivity;
import com.elinkway.infinitemovies.utils.BitmapUtils;
import com.elinkway.infinitemovies.utils.FileUtils;
import com.elinkway.infinitemovies.utils.ImageItem;
import com.elinkway.infinitemovies.utils.ImageUploadUtil;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.le123.ysdq.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by zhaopeipei on 2016/6/13.
 */
public class CopyrightFragment extends BaseFragment implements ImageUploadUtil.OnUploadProcessListener{
    private static final String TAG = "CopyrightFragment";
    public static final int TAKE_PICTURE = 1111;
    public static final int GET_PICTURE = 1112;
    private ReportActivity masterActivity;
    private GridView mGridItemPhotoView;
    private ReportPhotoAdapter mPhotoAdapter;
    public static Bitmap bitmap;
    private PopupWindow mPop;
    private LinearLayout mLinearPopupWindow;
    private View mPopView;
    private RelativeLayout mPopParent;
    private Button mBtCamera;
    private Button mBtFromPicture;
    private Button mCancel;
    private String mAid;
    private View mParentView;
    private int mSuccessNumber;
    private ArrayList<String> mAllPictureUrl = new ArrayList<>(); // 所有获得的图片链接，中间以逗号隔开
    private boolean isCreatedView;
    private EditText mContactEditText;
    private EditText mContactWayEditText;
    private EditText mLawyerName;

    @Override
    public void onAttach(Activity activity) {
        masterActivity = (ReportActivity) activity;
        super.onAttach(activity);
        super.setFragmentClassName(TAG);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LogUtils.e("CopyrightFragment", "CopyrightFragment onCreateView");
        mParentView = inflater.inflate(R.layout.fragment_copyright,
                container, false);
        initView(mParentView);
        initData();
        isCreatedView = true;
        return mParentView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtils.e(TAG, "setUserVisibleHint " + isVisibleToUser + " " + isCreatedView);
        ReportActivity tActivity = (ReportActivity) getActivity();
        if (tActivity != null) {
            tActivity.changeSubmitButtonState(true);
        }
        if (!isCreatedView) {
            return;
        }
        if (BitmapUtils.selectBitmap.size() > 0 && !TextUtils.isEmpty(mContactWayEditText.getText().toString())
                && !TextUtils.isEmpty(mLawyerName.getText().toString()) && !TextUtils.isEmpty(mContactEditText.getText().toString())) {
            masterActivity.notification(CopyrightFragment.this, true, 0);
        } else {
            masterActivity.notification(CopyrightFragment.this, false, 3);
        }
    }

    public void initView(View view) {
        mGridItemPhotoView = (GridView) view.findViewById(R.id.gv_report_grid_photo);
        mContactEditText = (EditText) view.findViewById(R.id.et_contact);
        mContactEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString()) && !TextUtils.isEmpty(mContactWayEditText.getText().toString())
                        && !TextUtils.isEmpty(mLawyerName.getText().toString()) && BitmapUtils.selectBitmap.size() > 0) {
                    masterActivity.notification(CopyrightFragment.this, true, 0);
                } else {
                    masterActivity.notification(CopyrightFragment.this, false, 3);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mContactWayEditText = (EditText) view.findViewById(R.id.ed_contact_way);
        mContactWayEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString()) && !TextUtils.isEmpty(mContactEditText.getText().toString())
                        && !TextUtils.isEmpty(mContactEditText.getText().toString()) && BitmapUtils.selectBitmap.size() > 0) {
                    masterActivity.notification(CopyrightFragment.this, true, 0);
                } else {
                    masterActivity.notification(CopyrightFragment.this, false, 3);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mLawyerName = (EditText) view.findViewById(R.id.ed_lawyer_name);
        mLawyerName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString()) && !TextUtils.isEmpty(mContactEditText.getText().toString())
                        && !TextUtils.isEmpty(mLawyerName.getText().toString()) && BitmapUtils.selectBitmap.size() > 0) {
                    masterActivity.notification(CopyrightFragment.this, true, 0);
                } else {
                    masterActivity.notification(CopyrightFragment.this, false, 3);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPopView = masterActivity.getLayoutInflater().inflate(R.layout.item_popupwindows, null);
        mLinearPopupWindow = (LinearLayout) mPopView.findViewById(R.id.ll_popup);
        mPopParent = (RelativeLayout) mPopView.findViewById(R.id.parent);
        mBtCamera = (Button) mPopView.findViewById(R.id.item_popupwindows_camera);
        mBtFromPicture = (Button) mPopView.findViewById(R.id.item_popupwindows_Photo);
        mCancel = (Button) mPopView.findViewById(R.id.item_popupwindows_cancel);
    }


    public void initData() {
        mAid = masterActivity.getIntent().getStringExtra("aid");
        mPop = new PopupWindow(masterActivity);
        mPop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPop.setBackgroundDrawable(new BitmapDrawable());
        mPop.setFocusable(true);
        mPop.setOutsideTouchable(true);
        mPop.setContentView(mPopView);
        mPopParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
                mLinearPopupWindow.clearAnimation();
            }
        });

        mBtCamera.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                photo();
                if (mPop == null || mLinearPopupWindow == null) {
                    return;
                }
                mPop.dismiss();
                mLinearPopupWindow.clearAnimation();
            }
        });
        mBtFromPicture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                BitmapUtils.copyImageItem(BitmapUtils.tempSelectBitmap, BitmapUtils.selectBitmap);
                Intent intent = new Intent(masterActivity,
                        AlbumActivity.class);
                startActivityForResult(intent, GET_PICTURE);
                masterActivity.overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                if (mPop == null || mLinearPopupWindow == null) {
                    return;
                }
                mPop.dismiss();
                mLinearPopupWindow.clearAnimation();
            }
        });
        mCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (mPop == null || mLinearPopupWindow == null) {
                    return;
                }
                mPop.dismiss();
                mLinearPopupWindow.clearAnimation();
            }
        });

        mPhotoAdapter = new ReportPhotoAdapter(masterActivity, masterActivity.getAid());
        mPhotoAdapter.setReportListener(new OnReportListener() {
            @Override
            public void onReportListener(boolean isNoFile) {
                if (isNoFile) {
                    masterActivity.sendMessage(4);
                }
            }
        });
        mPhotoAdapter.update();
        mGridItemPhotoView.setAdapter(mPhotoAdapter);
        mGridItemPhotoView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == BitmapUtils.selectBitmap.size()) {
                    if (mPop == null || mLinearPopupWindow == null) {
                        return;
                    }
                    mLinearPopupWindow.startAnimation(AnimationUtils.loadAnimation(masterActivity,
                            R.anim.activity_translate_in));
                    mPop.showAtLocation(mParentView, Gravity.BOTTOM, 0, 0);
                }
            }
        });
        if (TextUtils.isEmpty(masterActivity.getAid()) ||
                !masterActivity.getAid().equals(BitmapUtils.lastReportAid)) {
            return;
        }
        if (!TextUtils.isEmpty(BitmapUtils.reportContactPeople) && mContactEditText != null) {
            mContactEditText.setText(BitmapUtils.reportContactPeople);
        }
        if (!TextUtils.isEmpty(BitmapUtils.reportContactWay) && mContactWayEditText != null) {
            mContactWayEditText.setText(BitmapUtils.reportContactWay);
        }
        if (!TextUtils.isEmpty(BitmapUtils.reportLawyerName) && mLawyerName != null) {
            mLawyerName.setText(BitmapUtils.reportLawyerName);
        } 
        if (BitmapUtils.selectBitmap.size() > 0 && !TextUtils.isEmpty(mContactWayEditText.getText().toString())
                && !TextUtils.isEmpty(mLawyerName.getText().toString()) && !TextUtils.isEmpty(mContactEditText.getText().toString())) {
            masterActivity.notification(CopyrightFragment.this, true, 0);
        } else {
            masterActivity.notification(CopyrightFragment.this, false, 3);
        }
    }
    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.e(TAG, "onActivityResult " + requestCode + " " + resultCode);
        switch (requestCode) {
            case TAKE_PICTURE:
                if (BitmapUtils.selectBitmap.size() < 9 && resultCode == masterActivity.RESULT_OK) {

                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    FileUtils.saveBitmap(bm, fileName);

                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setBitmap(bm);
                    takePhoto.setImagePath(FileUtils.SDPATH + fileName + ".JPEG");
                    takePhoto.setBitFile(new File(takePhoto.getImagePath()));
                    BitmapUtils.selectBitmap.add(takePhoto);
                    if (mPhotoAdapter != null) {
                        mPhotoAdapter.update();
                    }
                    if (BitmapUtils.selectBitmap.size() > 0 && !TextUtils.isEmpty(mContactWayEditText.getText().toString())
                            && !TextUtils.isEmpty(mLawyerName.getText().toString()) && !TextUtils.isEmpty(mContactEditText.getText().toString())) {
                        masterActivity.notification(CopyrightFragment.this, true, 0);
                    } else {
                        masterActivity.notification(CopyrightFragment.this, false, 3);
                    }
                }
                break;
            case GET_PICTURE:
                if (mPhotoAdapter != null) {
                    mPhotoAdapter.update();
                }
                if (BitmapUtils.selectBitmap.size() > 0 && !TextUtils.isEmpty(mContactWayEditText.getText().toString())
                        && !TextUtils.isEmpty(mLawyerName.getText().toString()) && !TextUtils.isEmpty(mContactEditText.getText().toString())) {
                    masterActivity.notification(CopyrightFragment.this, true, 0);
                } else {
                    masterActivity.notification(CopyrightFragment.this, false, 3);
                }
                break;

        }
    }

    public void submit() {
        for (int i = 0; i < BitmapUtils.selectBitmap.size(); i++) {
            LogUtils.e(TAG, "Image Url is " + BitmapUtils.selectBitmap.get(i).getImagePath());
            UploadImageTask uploadImageTask = new UploadImageTask(masterActivity, this,
                    BitmapUtils.selectBitmap.get(i).getImagePath());
            uploadImageTask.execute();
        }
    }

    @Override
    public void onUploadDone(int responseCode, String message) {
//		ToastUtil.showShortToast(this, "头像上传成功");
        String imgUrl = "";
        String code = "";
        String msg = "";
        try {
            JSONObject result = new JSONObject(message);
            if(result != null){
                code = result.optString("code");
                imgUrl = result.optJSONObject("data").optString("url");
                msg = result.optString("msg");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BitmapUtils.upLoadPictureSize++;
        if ("200".equals(code)) {
            mSuccessNumber++;
        } else {
            LogUtils.e(TAG, "upload error ");
//            mHandler.sendEmptyMessage(3);
        }
        dealWithNewUrl(code, imgUrl, msg);
    }

    @Override
    public void onUploadProcess(int uploadSize) {
//		ToastUtil.showShortToast(this, "头像上传中");
    }

    @Override
    public void initUpload(int fileSize) {

    }

    private void dealWithNewUrl(String code, String url, String msg) {
        synchronized (this) {
            if (!TextUtils.isEmpty(url)) {
                mAllPictureUrl.add(url);
            }
        }
        if (mSuccessNumber == BitmapUtils.selectBitmap.size()) {
            UmengEventPoster.doEventPost(BigDataConstants.ILLEGAL_REPORT_SUBMIT);
            new uploadReportPictureTask(getActivity(), mAllPictureUrl.toString()
                    .replace("[", "").replace("]", ""), mAid, mContactEditText.getText().toString(),
                    mContactWayEditText.getText().toString(), mLawyerName.getText().toString()).start();
            BitmapUtils.selectBitmap.clear();
            BitmapUtils.tempSelectBitmap.clear();
            mHandler.sendEmptyMessage(1);
            BitmapUtils.reportContactWay = "";
            BitmapUtils.reportLawyerName = "";
            BitmapUtils.reportLawyerName = "";
//            BitmapUtils.copyImageItem(BitmapUtils.tempSelectBitmap, BitmapUtils.selectBitmap);
            if (mPhotoAdapter != null) {
                mPhotoAdapter.update();
            }
            masterActivity.sendMessage(1);
            mAllPictureUrl.clear();
            mSuccessNumber = 0;
            BitmapUtils.upLoadPictureSize = 0;
        } else if (mAllPictureUrl.size() == BitmapUtils.selectBitmap.size() ||
                BitmapUtils.upLoadPictureSize == BitmapUtils.selectBitmap.size()){
            masterActivity.sendMessage(3);
            BitmapUtils.upLoadPictureSize = 0;
            mSuccessNumber = 0;
            mAllPictureUrl.clear();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mContactEditText != null && !TextUtils.isEmpty(mContactEditText.getText().toString())) {
            BitmapUtils.reportContactPeople = mContactEditText.getText().toString();
            BitmapUtils.lastReportAid = masterActivity.getAid();
        }
        if (mContactWayEditText != null && !TextUtils.isEmpty(mContactWayEditText.getText().toString())) {
            BitmapUtils.reportContactWay = mContactWayEditText.getText().toString();
            BitmapUtils.lastReportAid = masterActivity.getAid();
        }
        if (mLawyerName != null && !TextUtils.isEmpty(mLawyerName.getText().toString())) {
            BitmapUtils.reportLawyerName = mLawyerName.getText().toString();
            BitmapUtils.lastReportAid = masterActivity.getAid();
        }
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    mContactEditText.setText("");
                    mContactWayEditText.setText("");
                    mLawyerName.setText("");
                    break;
            }
            super.handleMessage(msg);
        }
    };

}
